package com.steven.ourcontest.chat.view

import android.graphics.Rect
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import android.view.Window
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.viewModels
import androidx.core.view.get
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.steven.ourcontest.R
import com.steven.ourcontest.base.BaseActivity
import com.steven.ourcontest.chat.adapter.ChatOnLineViewBinder
import com.steven.ourcontest.chat.bean.ChatOnLineMessage
import com.steven.ourcontest.chat.bean.WSChatOnlineMessageResponse
import com.steven.ourcontest.chat.bean.WSMessageResponse
import com.steven.ourcontest.chat.helper.MessageHelper
import com.steven.ourcontest.chat.viewmodel.ChatViewModel
import com.steven.ourcontest.login.helper.LoginController
import com.steven.ourcontest.utils.RxBus
import com.steven.ourcontest.utils.changed
import com.steven.ourcontest.utils.plusAssign
import kotlinx.android.synthetic.main.activity_chat.*
import me.drakeet.multitype.Items
import me.drakeet.multitype.MultiTypeAdapter
import java.lang.Exception
import kotlin.math.abs

class ChatActivity : BaseActivity(isImmersed = true) {

    private val chatViewModel: ChatViewModel by viewModels()
    private val adapter by lazy {
        MultiTypeAdapter()
    }
    private val item by lazy {
        Items()
    }

    //由于bar横线导致decorview和contentview高度计算差值的问题
    private var difference = 0
    private var friendId = 0L
    private var name = ""
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun getViewId(): Int {
        return R.layout.activity_chat
    }

    override fun initView() {
        friendId = intent.getLongExtra("friendId", 0L)
        name = intent.getStringExtra("name") ?: ""
        if (friendId == 0L) {
            finish()
        }
        tv_name?.text = name
        MessageHelper.currentChatUid = friendId
        initKeyboardListener()
        rv_message?.adapter = adapter
        adapter.items = item
        adapter.register(ChatOnLineMessage::class.java, ChatOnLineViewBinder(this) {

        })
        chatViewModel.queryMessagesResponse.observe(this, {
            val size = adapter.items.size
            item.addAll(it.data)
            adapter.notifyItemInserted(size)
        })
        chatViewModel.sendMessagesResponse.observe(this, { success ->
            if (success) {
                //nothing yet
            } else {
                val view = rv_message?.getChildAt(0)
                val item = adapter.items[0]
                if (item is ChatOnLineMessage) {
                    item.sendError = true
                }
                if (view is ViewGroup) {
                    view.findViewById<ImageView>(R.id.iv_tips).isVisible = true
                }
            }
        })
        refresh?.setEnableRefresh(false)
        refresh?.setRefreshFooter(ClassicsFooter(this))
        refresh?.setEnableAutoLoadMore(false)
        refresh?.setOnLoadMoreListener {
            chatViewModel.queryMessage(friendId) {
                refresh?.finishLoadMore(true)
            }
        }
        et_content?.setOnClickListener {
            rv_message?.smoothScrollToPosition(0)
        }
        tv_confirm?.setOnClickListener {
            try {
                val message = et_content?.text.toString()
                item.add(0, ChatOnLineMessage(0, 0, 0, message, 0, System.currentTimeMillis(), "", LoginController.iconUrl))
                adapter.notifyDataSetChanged()
                rv_message?.smoothScrollToPosition(0)
                chatViewModel.sendMessage(friendId, message)
                et_content?.setText("")
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        chatViewModel.queryMessage(friendId)

        disposables += RxBus.getInstance()
            .toObservable(this, WSChatOnlineMessageResponse::class.java).subscribe {
                try {
                    item.add(0, it.data.first())
                    adapter.notifyDataSetChanged()
                    rv_message?.smoothScrollToPosition(0)
                    chatViewModel.updateMessageStatus(friendId)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        tv_confirm?.isClickable = false
        et_content?.changed {
            tv_confirm?.isClickable = it?.length ?: 0 > 0
        }
    }

    override fun onDestroy() {
        MessageHelper.currentChatUid = 0L
        super.onDestroy()
    }

    /**
     * 监听软键盘弹出
     */
    private fun initKeyboardListener() {
        val decorView: View = window.decorView
        val contentView: View = findViewById(Window.ID_ANDROID_CONTENT)
        decorView.viewTreeObserver.addOnGlobalLayoutListener(getGlobalLayoutListener(decorView, contentView))
    }

    /**
     * 软键盘弹出后的处理事件
     */
    private fun getGlobalLayoutListener(decorView: View, contentView: View): OnGlobalLayoutListener? {
        return OnGlobalLayoutListener {
            val rect = Rect()
            decorView.getWindowVisibleDisplayFrame(rect)
            val height: Int = decorView.context.resources.displayMetrics.heightPixels
            // 获取键盘抬高的高度
            val diff: Int = height - rect.height()
            if (abs(diff) in 1..199 && difference == 0) {
                difference = diff
            }
            if (diff > 0) {
                if (contentView.paddingBottom != diff) {
                    contentView.setPadding(0, 0, 0, diff - difference)
                }
            } else {
                if (contentView.paddingBottom != 0) {
                    contentView.setPadding(0, 0, 0, 0)
                }
            }
        }
    }
}